<template>
  <div class="line-chart" ref="lineChart"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, watch } from 'vue';
import type { PropType } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  name: 'LineChart',
  props: {
    // 使用 PropType 来定义属性类型
    temperatureData: {
      type: Array as PropType<number[]>,
      required: true,
    },
    humidityData: {
      type: Array as PropType<number[]>,
      required: true,
    },
    lightData: {
      type: Array as PropType<number[]>,
      required: true,
    },
  },
  setup(props) {
    const lineChart = ref<HTMLDivElement | null>(null);
    let chartInstance: echarts.ECharts | null = null; // 存储echarts实例

    // 初始化echarts
    const initChart = () => {
      if (lineChart.value) {
        chartInstance = echarts.init(lineChart.value);
      }
    };

    // 更新echarts的option
    const updateChart = () => {
      if (chartInstance) {
        const option = {
          title: {
            text: '温度、湿度和光照历史数据',
            subtext: '过去一周的变化趋势',
            left: 'center', // 标题居中
          },
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            data: ['温度', '湿度', '光照'],
            right: 50, // 图例靠右
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'], // 可以根据实际情况调整日期
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '温度',
              type: 'line',
              data: props.temperatureData,
              smooth: true,
            },
            {
              name: '湿度',
              type: 'line',
              data: props.humidityData,
              smooth: true,
            },
            {
              name: '光照',
              type: 'line',
              data: props.lightData,
              smooth: true,
            },
          ],
        };

        chartInstance.setOption(option); // 更新图表配置
      }
    };

    // 初始化图表
    onMounted(() => {
      initChart();
      updateChart();
    });

    // 监听props数据变化，重新更新图表
    watch(
        () => [props.temperatureData, props.humidityData, props.lightData],
        () => {
          updateChart();
        },
        { deep: true } // 需要深度监听数组中的变化
    );

    return { lineChart };
  },
});
</script>

<style scoped>
.line-chart {
  width: 100%;
  height: 100%;
}
</style>
